// https://www.lintcode.com/problem/binary-tree-level-sum/

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */

public class Solution {
    /**
     * @param root: the root of the binary tree
     * @param level: the depth of the target level
     * @return: An integer
     */
    public int levelSum(TreeNode root, int level) {
        // write your code here
        int ret = 0;
        int ilevel = 1;
        if ((root != null) && (level > 0)) {
            List<TreeNode> curr_nodes = new ArrayList<>();
            List<TreeNode> next_nodes = new ArrayList<>();
            curr_nodes.add(root);
            while (ilevel < level) {
                for (TreeNode node : curr_nodes) {
                    if (node.left != null) {
                        next_nodes.add(node.left);
                    }
                    if (node.right != null) {
                        next_nodes.add(node.right);
                    }
                }
                ++ilevel;
                curr_nodes.clear();
                for (TreeNode node : next_nodes) {
                    curr_nodes.add(node);
                }
                next_nodes.clear();
            }
            for (TreeNode node : curr_nodes) {
                ret += node.val;
            }
        }
        return ret;
    }
}